# -*- coding: utf-8 -*-

from app import app
from flask import render_template, redirect, url_for, request, flash
from forms import LoginForm, RegistrationForm, PostForm
from flask.ext.login import login_user, current_user, login_required, logout_user
from models import User
import leancloud
from flask_json import FlaskJSON, JsonError, json_response, as_json
from flask.ext.login import login_user
from helper import *
import hashlib

leancloud.init("po7YWHB3bjxCwOkLEyBbO0Y6-gzGzoHsz", "NkA8kxpPmtK3NHwgy6vVBls0")

@app.route('/')
def index():

	# 用户没有登录，跳转到登录页面，用户登陆了，跳转到我的应用页面
	if before_auth():
		return redirect(url_for('getapps', u_id=current_user.user_id.__str__()))

	return redirect(url_for('login'))


@app.route('/login', methods=['GET', 'POST'])
def login():
	form = LoginForm()
	if form.validate_on_submit():
		FUser = leancloud.Object.extend('FUser')
		query = FUser.query
		query.equal_to('f_u_name', form.username.data)
		query.equal_to('f_u_hash_password', hashlib.md5(form.password.data).hexdigest())
		query_list = query.find()

		if len(query_list) != 0:
			user = User(query_list[0])
			login_user(user, remember=form.remember_me.data)
			return redirect(request.args.get('next') or url_for('index'))
		flash(u'无效的用户名或密码')
	return render_template('login.html', form=form)


@app.route('/register', methods=['GET', 'POST'])
def register():
	form = RegistrationForm()
	if form.validate_on_submit():
		FUser = leancloud.Object.extend('FUser')
		user = FUser()
		user.set('f_u_name', form.username.data)
		user.set('f_u_email', form.mail.data)
		user.set('f_u_hash_password', hashlib.md5(form.password.data).hexdigest())
		user.save()
		flash(u'注册成功！请登录')
		return redirect(url_for('login'))
	return render_template('register.html', form=form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash(u'您已经退出。')
    return redirect(url_for('index'))


# 获取用户的APP列表
@app.route('/getapps', methods=['GET'])
def getapps():

	if before_auth() == False:
		return redirect(url_for('login'))

	if request.args.has_key('u_id'):
		u_id = request.args.get('u_id')

		FUserApp = leancloud.Object.extend('FUserApp')
		query = FUserApp.query
		query.equal_to('f_u_id', 1)
		userapps = query.find()

		if len(userapps) > 0:
			return render_template('apps.html', userapps=userapps)
	return render_template('apps.html', userapps=[])

# 编辑用户的自己的后台数据
@app.route('/edit', methods=['GET'])
def edit():

	if before_auth() == False:
		return redirect(url_for('login'))

	if request.args.has_key('app_id') and request.args.has_key('app_name'):

		FSCategory = leancloud.Object.extend('FSCategory')
		query = FSCategory.query
		query.equal_to('f_app_id', int(request.args.get('app_id')))
		categories = query.find()

		print len(categories)

		return render_template('edit.html', app_id=request.args.get('app_id'), app_name=request.args.get('app_name'), categories=categories)
	return "你又调皮了!!"

# 添加分类
@app.route('/addCategory', methods=['GET', 'POST'])
def addCategory():

	if before_auth() == False:
		return redirect(url_for('login'))

	if request.method == 'GET':
		if request.args.get('app_id') and request.args.get('app_name'):
			return render_template('addCategory.html', app_id=request.args.get('app_id'), app_name=request.args.get('app_name'))
		return "你有调皮了!!"
	if request.method == 'POST':
		if request.form.get('app_id') and request.form.get('category_name') and request.form.get('app_name'):
			
			FSCategory = leancloud.Object.extend('FSCategory')

			query = FSCategory.query
			query.equal_to('f_category_name', request.form.get('category_name'))
			query.equal_to('f_app_id', int(request.form.get('app_id')))
			categories = query.find()

			if len(categories) >= 1:
				return "分类名不能重复!"

			fsCategory = FSCategory()
			fsCategory.set('f_app_id', int(request.form.get('app_id')))
			fsCategory.set('f_category_name', request.form.get('category_name'))
			fsCategory.save()

			query.equal_to('f_app_id', int(request.form.get('app_id')))
			categories = query.find()

			return redirect(url_for('edit', app_id=request.form.get('app_id'), app_name=request.form.get('app_name'), categories=categories))

		return error_reply()

# 添加自己的产品
@app.route('/addProduct', methods=['GET', 'POST'])
def addProduct():

	if before_auth() == False:
		return redirect(url_for('login'))

	if request.method == 'GET':
		if request.args.has_key('category_id') and request.args.has_key('category_name'):
			return render_template('addProduct.html', category_id=request.args.get('category_id'), category_name=request.args.get('category_name'))
	if request.method == 'POST':
		if request.form.has_key('product_name') and request.form.has_key('product_image_url') and request.form.has_key('product_price') and request.form.has_key('product_introduce'):
			FSProduct = leancloud.Object.extend('FSProduct')
			fsProduct = FSProduct()
			fsProduct.set('f_category_id', int(request.form.get('category_id')))
			fsProduct.set('f_produce_name', request.form.get('product_name'))
			fsProduct.set('f_introduce', request.form.get('product_introduce'))
			fsProduct.set('f_image_url', request.form.get('product_image_url'))
			fsProduct.set('f_price', float(request.form.get('product_price')))
			fsProduct.save()

			return redirect(url_for('products', category_id=request.form.get('category_id'), category_name=request.form.get('category_name')))

	return error_reply()

# 查看分类下的商品
@app.route('/products', methods=['GET'])
def products():

	if before_auth() == False:
		return redirect(url_for('login'))

	if request.args.has_key('category_id') and request.args.has_key('category_name'):

		FSProduct = leancloud.Object.extend('FSProduct')
		query = FSProduct.query
		query.equal_to('f_category_id', int(request.args.get('category_id')))
		products = query.find()

		return render_template('products.html', category_id=request.args.get('category_id'), category_name=request.args.get('category_name'), products=products)
	return error_reply()

# 用户添加app
@app.route('/addApp', methods=['GET', 'POST'])
def addApp():

	if before_auth() == False:
		return redirect(url_for('login'))

	if request.method == 'GET':
		return render_template('addApp.html', u_id=current_user.user_id)
	if request.method == 'POST':
		if request.form.has_key('app_name') and request.form.has_key('app_image_url') and request.form.has_key('tokenValue'):

			FUserApp = leancloud.Object.extend('FUserApp')
			fUserApp = FUserApp()

			fUserApp.set('f_u_id', int(request.form.get('u_id')))
			fUserApp.set('f_app_logo_url', request.form.get('app_image_url'))
			fUserApp.set('f_app_name', request.form.get('app_name'))
			fUserApp.set('f_app_type', int(request.form.get('tokenValue')))
			fUserApp.save()

			return redirect(url_for('getapps', u_id=request.form.get('u_id')))
	return error_reply()


@app.route('/postlist', methods=['GET', 'POST'])
def postlist():

	
	FPost = leancloud.Object.extend('FPost')
	query = FPost.query
	postlist = query.find()
	print len(postlist)

	return render_template("postlist.html", app_id=request.args.get('app_id'), app_name=request.args.get('app_name'), products=postlist)



@app.route('/editpost', methods=['GET', 'POST'])
def editpost():
	form = PostForm()
	if form.validate_on_submit():
		FPost = leancloud.Object.extend('FPost')
		post = FPost()
		post.set('title', form.title.data)
		post.set('image', form.image.data)
		post.set('content', form.body.data)
		post.save()
		flash(u'添加文章成功!')
		return redirect(url_for('postlist'))

	return render_template('edit_post.html', form=form)